import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { Logger } from '../utils/log4js/log4js';
import Crypto from '../utils/secret/secret';
import { appConfig } from '../../config/config';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    const req = context.getArgByIndex(1).req;
    console.log('响应拦截:',req.headers);
    return next.handle().pipe(
      map((data) => {
        const logFormat = JSON.stringify({
          IP: req.ip,
          user: req.user,
          res_url: req.originalUrl,
          res_method: req.headers.method,
          data,
        });
        const crypto = new Crypto();
        Logger.info(logFormat);
        // const token = req.headers.authorization.slice(7);
        // const level = req.headers.level;
        // let times;
        // let signStr;
        // if (1 === Number(level)) {
        //   data = crypto.deAes(data);
        // } else if (2 === Number(level)) {
        //   times = new Date().getTime();
        //   signStr = crypto.sign(token, times, data);
        // } else if (3 === Number(level)) {
        //   data = crypto.deAes(data);
        //   times = new Date().getTime();
        //   signStr = crypto.sign(token, times, data);
        // }

        return {
          data,
          code: 200,
          // times,
          // signStr,
          msg: '请求成功!',
        };
      }),
    );
  }
}
